class Solution {
    int res = 0;
    public int countGoodNodes(int[][] edges) {
       int n = edges.length+1;
       List<Integer>[] g = new ArrayList[n];
       Arrays.setAll(g,i -> new ArrayList<>());
       for(int[] edge:edges)
       {
          int a = edge[0];
          int b = edge[1];
          g[a].add(b);
          g[b].add(a);
       }
       dfs(0,g,-1);
       return res;
    }
    public int dfs(int node,List<Integer>[] g,int parent)
    {
        int count =1;
        int ok=1;
        int cnt = 0;
        int flag=0;
        for(int var:g[node])
        {
            if(var!=parent)
            {
                cnt=dfs(var,g,node);
                if(flag==0) flag = cnt;
                if(flag!=cnt)
                {
                    ok=0;
                }
                count+=cnt;
            }
        }
        if(ok==1) res++;
        return count;
    }
}